import 'package:flutter/material.dart';
import 'package:flutter_architecture/constant/base_state_enum.dart';
import 'package:flutter_architecture/widgets/state/empty_state_widget.dart';
import 'package:flutter_architecture/widgets/state/error_state_widget.dart';
import 'package:flutter_architecture/widgets/state/loading_state_widget.dart';

///根据不同的网络请求状态显示不同的内容
/// @author: dingwen
/// @date: 2021/1/1

///正确显示数据的builder方法
typedef Builder = Widget Function(BuildContext context);

class MultiStateWidget extends StatefulWidget {
  ///加载中widget
  Widget loadingWidget;

  ///数据空widget
  Widget emptyWidget;

  ///错误widget
  Widget errorWidget;

  ///正确builder
  Builder builder;

  ///网络请求状态
  BaseState state;

  MultiStateWidget(
      {Key key,
      Builder builder,
      this.state,
      this.emptyWidget,
      this.loadingWidget,
      this.errorWidget})
      : super(key: key) {
    if (state == BaseState.CONTENT) {
      if (builder != null) {
        this.builder = builder;
      }
    }
    if (emptyWidget == null) {
      emptyWidget = EmptyStateWidget();
    }

    if (errorWidget == null) {
      errorWidget = ErrorStateWidget();
    }

    if (loadingWidget == null) {
      loadingWidget = LoadingStateWidget();
    }
  }

  @override
  _MultiStateWidgetState createState() => _MultiStateWidgetState();
}

class _MultiStateWidgetState extends State<MultiStateWidget> {
  @override
  Widget build(BuildContext context) {
    if (widget.state == null)
      return Container(
        width: 0,
        height: 0,
      );
    if (widget.state == BaseState.CONTENT) {
      return widget.builder(context);
    } else if (widget.state == BaseState.EMPTY) {
      return widget.emptyWidget;
    } else if (widget.state == BaseState.FAIL) {
      return widget.errorWidget;
    } else {
      return widget.loadingWidget;
    }
  }
}
